package logic

import (
	"context"
	"github.com/google/uuid"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"mall/app/auth/cmd/api/internal/constant"
	"mall/app/auth/cmd/api/internal/svc"
	"mall/app/auth/cmd/api/internal/types"
	"mall/app/thirdparty/cmd/rpc/pb"
	"mall/common/xerr"
	"strconv"
	"strings"
	"time"
)

type SendSmsCodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSendSmsCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsCodeLogic {
	return &SendSmsCodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SendSmsCodeLogic) SendSmsCode(req *types.SendSmsCodeReq) (*pb.SendSmsResp, error) {
	key := constant.SMS_CODE_CACHE_PREFIX + req.Phone

	// 接口防刷
	value, err := l.svcCtx.RedisClient.GetCtx(l.ctx, key)
	if err == nil && len(value) > 0 {
		t := strings.Split(value, "*")[1]
		last, _ := strconv.Atoi(t)
		if time.Now().Unix()-int64(last) < 60 {
			l.Infof("请求过与频繁 req: %+v", req)
			return nil, errors.Wrapf(xerr.NewErrorWithCode(xerr.SmsOverReq), "req: %v", req)
		}
	}

	// 存到redis

	random, _ := uuid.NewRandom()
	code := random.String()[:6]
	resp, err := l.svcCtx.ThirdPartyRpc.SendSmsCode(l.ctx, &pb.SendSmsReq{
		Phone: req.Phone,
		Code:  code,
	})
	if err != nil {
		l.Errorf("req: %+v err: %+v", req, err)
		return nil, err
	}
	err = l.svcCtx.RedisClient.SetexCtx(l.ctx, key, code+"*"+strconv.FormatInt(time.Now().Unix(), 10), 60*15)
	if err != nil {
		l.Errorf("req: %+v err: %+v", req, err)
		return nil, err
	}

	if err != nil {
		l.Errorf("req: %+v err: %+v", req, err)
		return nil, err
	}
	return resp, err

}
